package com.atguigu.msmservice.controller;

import com.atguigu.commonutils.R;
import com.atguigu.commonutils.utils.RandomUtil;
import com.atguigu.msmservice.service.MsmService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @program: book-shore
 * @description
 * @author: Pudding
 * @create: 2020-05-09 22:01
 **/
@RestController
@RequestMapping("/ucentapi/msm")
@CrossOrigin //跨域
public class MsmApiController {

    @Autowired
    private MsmService msmService;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @GetMapping(value = "/send/{phone}")
    public R code(@PathVariable String phone){
        //1 从redis根据手机号获取数据
        String code = redisTemplate.opsForValue().get(phone);
        //2 如果能取出数据直接返回
        if(!StringUtils.isEmpty(code)) return R.ok();
        //3 如果取不出来，调用接口发送短信
        //3.1生成验证码，随机四位数
        code = RandomUtil.getFourBitRandom();
        //3.2把生成的校验码封装到map里传递
        Map<String,Object> param = new HashMap<>();
        param.put("code",code);
        //3.3调用service方法
        boolean isSuccess = msmService.sendMsm(phone,param);
        //3.4发送成功把校验码放到redis
        if(isSuccess){
            //key:手机号，value：验证码
            redisTemplate.opsForValue().set(phone,code,10, TimeUnit.MINUTES);
            return R.ok();
        }else {
            return R.ok().message("信息发送失败！");
        }

    }

}
